﻿using System;
using System.Collections.Generic;
using System.Linq;
using OverStore.Configuration.Validation;
using OverStore.Exceptions.Configuration;
using OverStore.Runtime.OverStoreContext;
using OverStore.Runtime.ObjectRepository.ChangesTracker;

namespace OverStore.Configuration.ObjectRepository.ChangesTracker
{
    /// <summary>
    /// Contains configuration parameters allows to create instances of <see cref="ChecksumChangesTracker{TInstance, TIdentifier}"/>.
    /// </summary>
    /// <typeparam name="TInstance">The type of the instance.</typeparam>
    /// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
    public sealed class ChecksumObjectChangesTrackerConfiguration<TInstance, TIdentifier> : IComponentConfiguration<IChangesTracker<TInstance>>,
        ISupportValidation
        where TInstance : class
    {
        /// <summary>
        /// Gets or sets the collection of column names used for calculate checksum.
        /// </summary>
        /// <result>The columns.</result>
        public IEnumerable<string> Columns { get; set; }

        /// <summary>
        /// Creates the new instance of <see cref="IChangesTracker{TInstance}"/> type.
        /// </summary>
        /// <param name="context">The current context provides set of services may be used by changes tracker.</param>
        /// <returns>
        /// The new <see cref="IChangesTracker{TInstance}"/> instance.
        /// </returns>
        public IChangesTracker<TInstance> CreateComponent(IOverStoreContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (Columns == null || Columns.Count() == 0)
                throw this.ConfigurationException("Columns are missing.");
            return new ChecksumChangesTracker<TInstance, TIdentifier>(context.PersistenceServiceProvider, Columns.ToArray());
        }

        /// <summary>
        /// Perform component validation. Method should validate only
        /// component configuration itself, not sub components.
        /// If configuration is valid, null result should returns.
        /// </summary>
        /// <returns>
        ///     <see cref="T:OverStore.Configuration.ValidationResults"/> describes errors found in component configuration.
        /// </returns>
        public ValidationResult Validate()
        {
            return new ValidationResult(this)
                .AddError(Columns == null || Columns.Count() == 0, "At least one column should be specified for checksum changes tracker.");
        }
    }
}